<?php
/**
 * ------------------------------------------------------------------------
 * JA Disqus Debate Echo plugin for Joomla 2.5
 * ------------------------------------------------------------------------
 * Copyright (C) 2004-2011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
 * @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
 * Author: J.O.O.M Solutions Co., Ltd
 * Websites: http://www.joomlart.com - http://www.joomlancers.com
 * ------------------------------------------------------------------------
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

/**
 *
 * JA DISQUS DEBATE ECHO CLASS
 * @author JoomlArt
 *
 */
class plgContentJADisqus_debate_echo extends JPlugin
{
    var $_plgCode = '#{jacomment(.*?)}#i';
    var $_plgCodeDisable = '#{jacomment(\s*)disable}#i';

    var $_url = "";
    var $_path = "";
    var $_postid = "";

    var $source = "both";
    var $provider = "intensedebate";
    var $_comments = array();
    var $_commentsID = array();


    /**
     *
     * Construct method
     * @param object $subject
     * @param object $config
     */
    function plgContentJADisqus_debate_echo(&$subject, $config)
    {
        parent::__construct($subject, $config);

        $this->plugin = &JPluginHelper::getPlugin('content', 'jadisqus_debate_echo');
        $this->plgParams = new JRegistry();
        $this->plgParams->loadJSON($this->plugin->params);
        $this->source = $this->plgParams->get('source', 'both');
        $provider = $this->plgParams->get('provider', 'intensedebate');
        switch ($provider) {
            case 'disqus':
                $provider = 'disqus';
                break;
            case 'jskit':
                $provider = 'jskit';
                break;
            case 'intensdebate':
                $provider = 'intensedebate';
                break;
            default:
                $provider = 'intensedebate';
                break;
        }
        $this->provider = $provider;
        $this->stylesheet($this->plugin);
    }


    /**
     *
     * Process content before display
     * @param string $context key type component
     * @param object $article
     * @param object $params
     * @param int $limitstart
     * @return unknown
     */
    function onContentBeforeDisplay($context, &$article, &$params, $limitstart = 0)
    {
        if (!$this->isDetailPage()) {
            //it is not called from detail view
            $return = $this->getDisqusContent($context, $article, $params, $limitstart, "introtext");
            return $return;
        }
        return;
    }


    /**
     *
     * Process content
     * @param string $context key type component
     * @param object $article
     * @param object $params
     * @param int $limitstart
     * @return unknown
     */
    function onContentPrepare($context, &$article, &$params, $limitstart = 0)
    {
        if ($this->isDetailPage()) {
            //it is not called from detail view
            $return = $this->getDisqusContent($context, $article, $params, $limitstart);
            return $return;
        }
        return;
    }


    /**
     *
     * Parse content with disqus
     * @param string $context
     * @param object $article
     * @param object $params
     * @param int $limitstart
     * @param string $typeText
     * @return unknown
     */
    function getDisqusContent($context, &$article, &$params, $limitstart, $typeText = "text")
    {
        if (($this->source=="com_k2")&& (!$this->checkComponent('com_k2')))
		{
			return;
		}
		$mainframe = JFactory::getApplication();
        global $option;
        static $count = 0;

        static $addedUrls = array();
        //$sectionid      = $article->sectionid;
        $check = true;
        if (!isset($article->catid)) {
            $article->catid = 0;
        }

        if (!isset($article->text) && empty($article->text)) {
            $article->text = "";
        }

        if (!isset($article->text)) {
            $article->introtext = isset($article->fulltext) ? $article->fulltext : isset($article->introtext) ? $article->introtext : "";
        }
        $catid = $article->catid;
        $option = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $itemid = JRequest::getInt('Itemid');
        $id = JRequest::getInt('id');
        //
        $plugin = $this->plugin;
        $plgParams = $this->plgParams;
        //
        if (!isset($article->id) || !$article->id) {
            return '';
        }
        if ($this->source != 'both' && $this->source != $option) {
            $check = false;
        }

        $display_on_home = (int) $plgParams->get('display_on_home', 1);
        if ($view == 'featured' && $display_on_home != 1) {
            $check = false;
        }

        $display_on_list = (int) $plgParams->get('display_on_list', 1);
        if ((($option == 'com_k2' && $view != 'item') || ($option == 'com_content' && $view != 'article' && $view != 'featured')) && $display_on_list != 1) {
            $check = false;
        }

        if ($this->isDetailPage()) {
            //it is not called from detail view
            if ($id && $id != $article->id) {
                $check = false;
            }
        }
        $tmp_text = isset($article->text) ? $article->text : isset($article->introtext) ? $article->introtext : "";
        if (isset($article->text)) {
            if (preg_match($this->_plgCodeDisable, $tmp_text)) {
                $check = false;
            }
        }
        if (!$check) {
            $article->text = $this->removeCode($tmp_text);
            return;
        }

        $isComment = false;

        //GET PLUGIN CONFIG
        $mode = $plgParams->get('mode', 'automatic');

        if ($this->isContentItem($article)) {
            $catids = $plgParams->get('mode-automatic-catsid', '');
        } else {
            $catids = $plgParams->get('mode-automatic-k2catsid', '');
        }
        $tagmode = $plgParams->get('tagmode', 0);
        $display_comment_count = $plgParams->get('display_comment_count', 1);
        //
        $user = & JFactory::getUser();
        $document = & JFactory::getDocument();
        $this->document = & $document;

        //CHECK PAGE WAS SELECTED TO DISPLAY COMMENT FORM
        switch ($mode) {
            case 'disable':
                $article->text = $this->removeCode($article->text);
                return;
                break;
            case 'manual':
                if (!preg_match($this->_plgCode, $article->text)) {
                    return;
                }
                break;
            case 'automatic':
            default:
                if (is_array($catids)) {
                    if ($catids[0] == '') {
                        $categories[] = $catid;
                    } else {
                        $categories = $catids;
                    }
                } elseif ($catids == '') {
                    $categories[] = $catid;
                } else {
                    $categories[] = $catids;
                }
                if (!(in_array($catid, $categories) || preg_match($this->_plgCode, $article->text))) {
                    return;
                }
                break;
        }
        //END OF CHECK
        $text = !empty($typeText) ? $typeText : "text";
        $authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));

        if (in_array($article->access, $authorised)) {
            if ($option == "com_content") {
                if (!isset($article->catslug)) {
                    $article->catslug = $article->catid . ':' . $article->category_alias;
                }
                $this->_path = JRoute::_(ContentHelperRoute::getArticleRoute($article->slug, $article->catslug));
            } elseif ($option == "com_k2") {
                if ($this->isDetailPage()) {
                    //priority: text->fulltext->introtext
                    $text = isset($article->text) ? 'text' : (isset($article->fulltext) ? 'fulltext' : 'introtext');
                } else {
                    //priority: introtext->text->fulltext
                    $text = isset($article->introtext) ? 'introtext' : (isset($article->text) ? 'text' : 'fulltext');
                }
                $this->_path = K2HelperRoute::getItemRoute($article->id, $article->catid);
            } else {
                $this->_path = "#";
            }

        } else {
            $this->_path = JRoute::_("index.php?option=com_user&view=login");
        }

        if (!preg_match('/^\//', $this->_path)) {
            //convert to relative url
            $this->_path = JURI::root(true) . '/' . $this->_path;
        }
        //convert to absolute url
        $this->_url = $this->getRootUrl() . $this->_path;

        $this->_sefurl = $this->convertUrl($this->_path);
        $this->_sefpath = $this->convertUrl($this->_path, true);

        if (in_array($this->_url, $addedUrls)) {
            return;
        }
        $addedUrls[] = $this->_url;

        if (($option == "com_content" && $view == 'article') || ($option == "com_k2" && $view == 'item')) {
            $isComment = true;
        }

        $this->_postid = md5($this->_url);

        if (!$isComment and $display_comment_count == 0) {
            return;
        }

        $this->isComment = $isComment;

        $provider = $this->provider;
        $output = $this->loadLayout($this->plugin, $provider);
        /**
         * JS Loading Optimize
         * create place holder for comment
         */
        $uniqueID = $this->_postid;
        $container = 'JaCommentContainer' . $uniqueID;
        $holder = 'JaCommentPlaceHolder' . $uniqueID;
        $store = &Plg_comment_storage::getInstance();
        $store->_comments[] = '<div id="' . $container . '">' . $output . '</div>';
        $store->_commentsID[] = $uniqueID;

        $output = '<div id="' . $holder . '"></div>';
        if (isset($article->$text)) {
            if ($mode == 'manual' || preg_match($this->_plgCode, $article->$text)) {
                $article->$text = preg_replace($this->_plgCode, $output, $article->$text);
            } else {
                $article->$text .= $output;
            }
        }
        return;
    }


    /**
     *
     * @return (string) - root url without last slashes
     */
    function getRootUrl()
    {
        $url = str_replace(JURI::root(true), '', JURI::root());
        $url = preg_replace('/\/+$/', '', $url);

        return $url;
    }


    /**
     *
     * Detect page detail for disqus
     * @return boolean
     */
    function isDetailPage()
    {
        $option = JRequest::getVar('option');
        $view = JRequest::getVar('view');
        //if its a detail page
        if (($option == 'com_k2' && $view == 'item') || ($option == 'com_content' && $view == 'article')) {
            return true;
        }
        return false;
    }


    /**
     *
     * Validate is content article
     * @param object $article
     * @return boolean
     */
    function isContentItem($article)
    {
        return isset($article->xreference) ? true : false;
    }


    /**
     * convert from normal format to sef format
     *
     * @param unknown_type $matches
     * @return unknown
     */
    function convertUrl($originalPath, $pathonly = false)
    {
        jimport('joomla.application.router');
        // Get the router
        $router = new JRouterSite(array('mode' => JROUTER_MODE_SEF));

        // Make sure that we have our router
        if (!$router) {
            if ($pathonly)
                return $originalPath;
            else
                return $this->getRootUrl() . $originalPath;
        }

        // Build route
        $path = str_replace(JURI::root(true), '', $originalPath);
        $uri = &$router->build($path);

        $path = $uri->toString(array('path', 'query', 'fragment'));
        if (!preg_match('/^\/+/', $path)) {
            $path = "/{$path}";
        }

        //
        if ($pathonly) {
            return $path;
        } else {
            $url = $this->getRootUrl();
            return $url . $path;
        }
    }


    /**
     *
     * Process content after render
     * @return string
     */
    function onAfterRender()
    {

        $store = &Plg_comment_storage::getInstance();
        $this->_comments = $store->_comments;
        $this->_commentsID = $store->_commentsID;

        $body = JResponse::getBody();
        $comments = $this->loadLayout($this->plugin, 'common');
        $countscript = "";
        $body = str_replace('</body>', $comments . "\n</body>", $body);

        if ($this->provider == 'disqus') {
            $countscript = $this->loadLayout($this->plugin, 'disqus_count');
            $body = str_replace('</body>', $countscript . "\n</body>", $body);
        }
        JResponse::setBody($body);
    }


    /**
     *
     * Remove comment tag code
     * @param string $content
     * @return string
     */
    function removeCode($content)
    {
        return preg_replace($this->_plgCode, '', $content);
    }


    /**
     *
     * Get Layout for display
     * @param object $plugin
     * @param string $layout
     * @return string
     */
    function getLayoutPath($plugin, $layout = 'default')
    {
        $mainframe = JFactory::getApplication();

        // Build the template and base path for the layout
        $tPath = JPATH_BASE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'html' . DS . $plugin->name . DS . $layout . '.php';
        $bPath = JPATH_BASE . DS . 'plugins' . DS . $plugin->type . DS . $plugin->name . DS . 'tmpl' . DS . $layout . '.php';

        // If the template has a layout override use it
        if (file_exists($tPath)) {

            return $tPath;

        } elseif (file_exists($bPath)) {

            return $bPath;

        }
        return '';
    }


    /**
     *
     * Display content
     * @param object $plugin
     * @param string $layout
     * @return string
     */
    function loadLayout($plugin, $layout = 'default')
    {
        $layout_path = $this->getLayoutPath($plugin, $layout);
        if ($layout_path) {
            ob_start();
            require $layout_path;
            $content = ob_get_contents();
            ob_end_clean();
            return $content;
        }
        return '';
    }


    /**
     *
     * Set style for content display
     * @param object $plugin
     * @return unknown
     */
    function stylesheet($plugin)
    {
        $mainframe = JFactory::getApplication();
        JHTML::stylesheet('plugins/' . $plugin->type . '/' . $plugin->name . '/' . 'style.css');
        if (is_file(JPATH_SITE . DS . 'templates' . DS . $mainframe->getTemplate() . DS . 'css' . DS . $plugin->name . ".css"))
            JHTML::stylesheet('templates/' . $mainframe->getTemplate() . '/css/' . $plugin->name . ".css");
    }
	
	/**
     *
     * Check component is existed
     * @param string $component component name
     * @return int return > 0 when component is installed
     */
    function checkComponent($component)
    {
        $db = JFactory::getDBO();
        $query = " SELECT Count(*) FROM #__extensions as e WHERE e.element ='$component' and e.enabled=1";
        $db->setQuery($query);
        return $db->loadResult();
    }
	
}
/**
 *
 * Comment Storage plugin class
 * @author JoomlArt
 *
 */
class Plg_comment_storage
{
    var $_comments = array();
    var $_commentsID = array();


    /**
     *
     * Get Instance of Comment Store
     * @return object
     */
    function &getInstance()
    {
        static $instance = null;

        if ($instance == null) {
            $instance = new Plg_comment_storage();
        }

        return $instance;
    }
}

?>